#include "procedure.h"

namespace IAlib
{

Procedure::Procedure(): m_name(""), m_efficiency(0)
{
}

Procedure::Procedure(const Procedure &procedure)
{
    m_name = procedure.m_name;
    m_efficiency = procedure.m_efficiency;
    for (int i = 0; i <  procedure.getActions().size(); i++)
    {
        addAction(*procedure.getActions()[i]);
    }
}

Procedure::~Procedure()
{
    for (int i = 0; i < m_actions.size(); i++)
    {
        delete(m_actions[i]);
    }
}

void Procedure::addAction(const ItsAction &action)
{
    ItsAction * newAction = new ItsAction(action);
    m_actions.append(newAction);
}

void Procedure::removeAction(const QString& id)
{
	for (int i = 0; i < m_actions.size(); i++)
	{
		if (m_actions[i]->getActionId() == id)
		{
			m_actions.removeAt(i);
			i--;
		}
	}
}

void Procedure::removeActionAt(const int index)
{
	if (index >= 0 && index < m_actions.size())
    {
		m_actions.removeAt(index);
	}
}


ItsAction * Procedure::getAction(const int index)
{
    if (index >= 0 && index < m_actions.size())
    {
        return m_actions[index];
    }
    else
    {
        return NULL;
    }
}

QDomElement Procedure::toXML(QDomDocument &doc)
{
    QDomElement ele = doc.createElement("procedure");
    ele.setAttribute("name", m_name);
    ele.setAttribute("efficiency", m_efficiency);
    QDomElement actions = doc.createElement("ItsActions");
    for (int i = 0; i < m_actions.size(); i++)
    {
        actions.appendChild(m_actions[i]->toXML(doc));
    }
    ele.appendChild(actions);
    return ele;
}

void Procedure::fromXML(QDomElement ele)
{
    m_name = ele.attribute("name", "");
    m_efficiency = ele.attribute("efficiency","").toInt();
    QDomNode n = ele.firstChild();
    while (!n.isNull())
    {
        QDomElement e = n.toElement();
        if (e.tagName() == "ItsActions")
        {
            QDomNode actionNode = e.firstChild();
            while (!actionNode.isNull())
            {
                ItsAction action;
                action.fromXML(actionNode.toElement());
                addAction(action);
                actionNode = actionNode.nextSibling();
            }
        }
        n = n.nextSibling();
    }
}

Procedure& Procedure::operator=(const Procedure& procedure)
{
    m_name = procedure.m_name;
    m_efficiency = procedure.m_efficiency;
    for (int i = 0; i < m_actions.size(); i++)
    {
        delete(m_actions[i]);
    }
    m_actions.clear();
    for (int i = 0; i <  procedure.getActions().size(); i++)
    {
        addAction(*procedure.getActions()[i]);
    }
    return *this;
}

}


